'''
Created on Jan 29, 2010

@author: mkiyer
'''

oncoseq_path = '/archive10/bowtie/Sample_Parameters'
pooling_file_ext = 'pooling-info.txt'
coverage_file_ext = 'coverage_summary.txt'
read_length = 32

if __name__ == '__main__':
    import sys
    import os
    import re
    
    sample_name = sys.argv[1]
    out_file = sys.stdout
    
    sample_path = os.path.join(oncoseq_path, sample_name)    
    assert os.path.exists(sample_path)
    
    # get pooling info
    pooling_file = os.path.join(sample_path, 'Current', '%s.%s' % (sample_name, pooling_file_ext))
    assert os.path.exists(pooling_file)
    
    total_reads = None
    mapped_reads = None
    human_mapped_reads = None
    splice_mapped_reads = None
    
    for line in open(pooling_file):
        m = re.match('Total reads: (.+)', line)        
        if m != None:
            total_reads = int(m.group(1))
            continue
        m = re.match('Mapped reads: (.+)', line)
        if m != None:
            mapped_reads = int(m.group(1))
            continue
        m = re.match('Human-mapped reads: (.+)', line)
        if m != None:
            human_mapped_reads = int(m.group(1))
            continue
        m = re.match('Splice-mapped reads: (.+)', line)
        if m != None:
            splice_mapped_reads = int(m.group(1))
            continue

    # calculate normalization factor
    norm_factor = (1.0e9) / (read_length * human_mapped_reads)

    # process coverage file
    coverage_file = os.path.join(sample_path, 'Current', '%s.%s' % (sample_name, coverage_file_ext))
    for line in open(coverage_file):
        if line.startswith('fixedStep'):
            out_file.write(line)
        else:
            # get coverage
            cov = int(line.split('\t')[0])
            # normalize
            cov *= norm_factor
            # output
            out_file.write('%.2f\n' % cov)    
